<?php

class PageListManager
{
    /**
     * Return all pages and applications administered by the user, in an associative
     * array <page_id> => <Page object>.
     */
    public static function getInstalledPages()
    {
        $pages = self::getPagesArray();
        if (empty($pages))
            return array();

        $q = Doctrine_Query::create()
            ->from('Page p')
            ->innerJoin('p.Profile pp') // Filter out non-installed pages
            ->whereIn('p.page_id', array_keys($pages));

        $page_list = array();
        foreach ($q->execute() as $page)
            $page_list[$page->page_id] = $page;
        return $page_list;
    }


    public static function getInstalledPagesArray()
    {
        $pages = self::getPagesArray(null);
        self::updateInstalledPages($pages);
        foreach ($pages as $page_id => $p)
            if (!$p['is_installed'])
                unset($pages[$page_id]);
        uasort($pages, array(__CLASS__, 'sortByPageName'));
        return $pages;
    }


    public static function getAllPagesArray($access_token)
    {
        $pages = self::getPagesArray($access_token);
        self::updateInstalledPages($pages);
        uasort($pages, array(__CLASS__, 'sortByPageName'));
        return $pages;
    }


    private static function getPagesArray($access_token)
    {
        $pages = array();
        try {
            $uid = sfContext::getInstance()->getUser()->getUid();  
            $r = App::call_api(array(
                    'method'  => 'fql.multiquery',
                    'queries' => json_encode(array(
                            'pages' => 'SELECT page_id, name, pic_square, page_url, has_added_app FROM page WHERE page_id IN (SELECT page_id FROM page_admin WHERE uid = '.$uid.') OR page_id IN (SELECT application_id FROM developer WHERE developer_id = '.$uid.')',
                            'apps'  => 'SELECT app_id, display_name, logo_url FROM application WHERE app_id IN (SELECT application_id FROM developer WHERE developer_id = '.$uid.')',
                            )),
                    'access_token' => $access_token,
                    ));        

            foreach (App::getFQLResultSet($r, 'pages') as $rs)
                $pages[$rs['page_id']] = array(
                    'name'         => $rs['name'],
                    'picture'      => $rs['pic_square'],
                    'link'         => $rs['page_url'],
                    'type'         => 'page',
                    'is_added'     => (bool) $rs['has_added_app'],
                    'is_installed' => false,
                    'is_admin'     => false, // is_added && is_installed
                    );

            foreach (App::getFQLResultSet($r, 'apps') as $rs) {
                if (array_key_exists($rs['app_id'], $pages)) {
                    if (!$pages[$rs['app_id']]['name'])
                        $pages[$rs['app_id']]['name'] = $rs['display_name'];
                    $pages[$rs['app_id']]['type'] = 'application';
                }
            }
        } catch (Exception $e) {
            sfContext::getInstance()->getLogger()->err('{step1Action} getAllPagesArray: '.$e->getMessage());
        }

        return $pages;
    }


    private static function updateInstalledPages(&$pages)
    {
        if (empty($pages))
            return; // ->whereIn('x', array()) does not work as expected

        $q = Doctrine_Query::create()
            ->from('PageProfile p')
            ->select('p.page_id')
            ->whereIn('p.page_id', array_keys($pages));

        foreach ($q->execute(array(), Doctrine_Core::HYDRATE_SCALAR) as $page) {
            $pages[$page['p_page_id']]['is_installed'] = true;
            $pages[$page['p_page_id']]['is_admin'] = $pages[$page['p_page_id']]['is_added'];
        }
    }


    private static function sortByPageName($page_a, $page_b)
    {
        if ($page_a['is_admin'] !== $page_b['is_admin'])
            return ($page_a['is_admin'] ? 1 : -1);
        else
            return strcmp($page_a['name'], $page_b['name']);
    }
}

